/**
 * 存储管理对象
 * 目标：将现有系统的所有需要存储的数据，统一管理
 *
 * @author will
 * @site https://merchant.jdyd.xyz
 * @date 2022/04/13 07:18
 */
import { sm4EncryptByReqData, sm4DecryptByResData } from '@/util/encryptUtil.js'
import appConfig from '@/config/appConfig.js'

const payOpenIdKey = sm4EncryptByReqData('payOpenId',true).encryptData
const fansIdKey = sm4EncryptByReqData('fansId',true).encryptData
const userIdKey = sm4EncryptByReqData('userId',true).encryptData
// const placeOpenIdKey = sm4EncryptByReqData('placeOpenId',true).encryptData
const currentUserInfoKey = sm4EncryptByReqData('currentUserInfo',true).encryptData
const liteOpenIdKey = sm4EncryptByReqData('liteOpenId',true).encryptData

let GZ_TOKEN = ''
const model = {

	// 获取和放置token
	token: (val, isDelete = false) => {

		if (isDelete) {
			appConfig.tokenVal = ''
			return uni.removeStorageSync(appConfig.tokenKey)
		}

		if (val) { // 有值，为放置
			appConfig.tokenVal = val
			uni.setStorageSync(appConfig.tokenKey, val)

		} else { // 否则为获取

			if (!appConfig.tokenVal) { //缓存取不到，获取应用本地信息
				appConfig.tokenVal = uni.getStorageSync(appConfig.tokenKey)
			}
			return appConfig.tokenVal

		}
	},
	// 获取和放置密钥
	dataKey: (val, isDelete = false) => {
	
		if (isDelete) {
			appConfig.dataKeyVal = ''
			return uni.removeStorageSync(appConfig.dataKeyKey)
		}
	
		if (val) { // 有值，为放置
			appConfig.dataKeyVal = val
			uni.setStorageSync(appConfig.dataKeyKey, val)
	
		} else { // 否则为获取
	
			if (!appConfig.dataKeyVal) { //缓存取不到，获取应用本地信息
				appConfig.dataKeyVal = uni.getStorageSync(appConfig.dataKeyKey)
			}
			return appConfig.dataKeyVal
	
		}
	},
	// 获取和放置归属网点列表
	bAgent: (val, isDelete = false) => {
	
		if (isDelete) {
			appConfig.agentKey = ''
			return uni.removeStorageSync(appConfig.agentKey)
		}
	
		if (val) { // 有值，为放置
			appConfig.agentVal = val
			uni.setStorageSync(appConfig.agentKey, val)
	
		} else { // 否则为获取
	
			if (!appConfig.agentVal) { //缓存取不到，获取应用本地信息
				appConfig.agentVal = uni.getStorageSync(appConfig.agentKey)
			}
			return appConfig.agentVal
	
		}
	},
	version: (val, isDelete = false) => {
		if(isDelete){
			appConfig.versionVal = ''
			return uni.removeStorageSync(appConfig.versionKey)
		}
		if (val !== undefined && val !== null) { // 有值，为放置
			appConfig.versionVal = val
			uni.setStorageSync(appConfig.versionKey, val)
			
		} else { // 否则为获取
			
			if (!appConfig.versionVal) { //缓存取不到，获取应用本地信息
				appConfig.versionVal = uni.getStorageSync(appConfig.versionKey)
			}
			return appConfig.versionVal
			
		}
	},
	// 设置token
	setToken(tokenValue) {

		GZ_TOKEN = tokenValue
		return uni.setStorageSync(appConfig.tokenKey, tokenValue)
	},
	// 存储userId
	setUserId(userId) {
	
		USERID = userId
		return uni.setStorageSync(appConfig.tokenKey, tokenValue)
	},
	// 已经登录的用户记录
	loggedInUser: (addUserName = null, removeUserName = null) => {

		let key = 'loggedInUserList'

		// 删除
		if (removeUserName) {
			let nameList = uni.getStorageSync(key) || []
			if (nameList.length <= 0) { //不存在数据
				return false
			}

			let hasUserIndex = nameList.indexOf(removeUserName)
			if (hasUserIndex >= 0) {
				nameList.splice(hasUserIndex, 1) //删除
				uni.setStorageSync(key, nameList)
			}

			return false;
		}

		// 有新插入的记录
		if (addUserName) {
			let nameList = uni.getStorageSync(key) || []

			let hasUser = false
			for (let i = 0; i < nameList.length; i++) {
				if (nameList[i] == addUserName) {
					hasUser = true;
				}
			}

			// 包含记录
			if (hasUser) {
				return false;
			}

			// 最多存储 5 个
			if (nameList.length >= 5) {
				nameList.splice(0, 1) //删除第一个
			}
			nameList.push(addUserName)
			uni.setStorageSync(key, nameList)


			//获取	
		} else {
			return uni.getStorageSync(key) || []; //默认空数组
		}
	},

	// 用户信息
	userInfo: (currentUserInfo, isDelete = false) => {
		
		if(isDelete){
			return uni.removeStorageSync(currentUserInfoKey)
		}

		if (currentUserInfo) {
			// 仅保存基础数据
			let saveUser = {
				currentScore: currentUserInfo.currentScore,
				fansId: currentUserInfo.fansId,
				headPic: currentUserInfo.headPic,
				isAuth: currentUserInfo.isAuth,
				mchNo: currentUserInfo.mchNo,
				nickName: currentUserInfo.nickName,
				sex: currentUserInfo.sex,
				starLevel: currentUserInfo.starLevel,
				phone: currentUserInfo.phone,
				realName: currentUserInfo.realName,
				birthday: currentUserInfo.birthday,
				khjlAgentNo: currentUserInfo.khjlAgentNo,
				gswdAgentNo: currentUserInfo.gswdAgentNo,
				gswdAgentName: currentUserInfo.gswdAgentName,
				gswdPid: currentUserInfo.gswdPid,
				assetLevel:currentUserInfo.assetLevel,
				currentScore:currentUserInfo.currentScore,
				openId:currentUserInfo.openId,
				updatedAt:currentUserInfo.updatedAt,
				assetLevelDate:currentUserInfo.assetLevelDate,	// 数据来源
				levelScore:currentUserInfo.levelScore,	// 每月可享受福分
				custNolist:currentUserInfo.custNolist,//会员等级
				inSearch:currentUserInfo.inSearch, //上个月资产等是否核算中
				year:currentUserInfo.year,//年
				quarter:currentUserInfo.quarter,//季度
				quarterAssetLevel:currentUserInfo.quarterAssetLevel,//季度资产等级
				quarterInSearch:currentUserInfo.quarterInSearch,//是否查询到季度资产登记0查询到了1没查询到
				
			}
			return uni.setStorageSync(currentUserInfoKey,sm4EncryptByReqData({ originData: saveUser },true).encryptData)
		}
		return sm4DecryptByResData(uni.getStorageSync(currentUserInfoKey),true)
	},
	// 项目环境变量：（测试、 生产的切换）
	env: (envMode) => {
		if (envMode) {
			uni.setStorageSync('currentEnvEnum', envMode) // 改变存储
		}
		return uni.getStorageSync('currentEnvEnum')
	},
	fansId: (val, isDelete = false) => {
		if (isDelete) {
			return uni.removeStorageSync(fansIdKey)
		}
		if(val){
			uni.setStorageSync(fansIdKey,sm4EncryptByReqData({ originData: val },true).encryptData)
		}else{
			return sm4DecryptByResData(uni.getStorageSync(fansIdKey),true)
		}
	},
	userId: (val) => {
		if(val){
			uni.setStorageSync(userIdKey,sm4EncryptByReqData({ originData: val },true).encryptData)
		}else{
			return sm4DecryptByResData(uni.getStorageSync(userIdKey),true)
		}
	},
	// 地域公众号opendId(appId作为key值)
	placeOpenId: (key, val, isDelete = false) => {
		if (isDelete) {
			uni.removeStorageSync(key)
			return
		}
		if (key && val) {
			uni.setStorageSync(key,val)
		}
		return uni.getStorageSync(key)
	},
	// 支付公众号openId
	payOpenId: (val) => {
		if (val) {
			return uni.setStorageSync(payOpenIdKey,sm4EncryptByReqData({ originData: val },true).encryptData)
		}
		return sm4DecryptByResData(uni.getStorageSync(payOpenIdKey),true)
	},
	/**
	 * 三方出资 openId
	 * @param { String } key `${ifCode}-openId`
	 * @param { String } val openId
	 */
	openId: (key,val) => {
		if (val) {
			return uni.setStorageSync(sm4EncryptByReqData(key,true).encryptData,sm4EncryptByReqData({ originData: val },true).encryptData)
		}
		return sm4DecryptByResData(uni.getStorageSync(sm4EncryptByReqData(key,true).encryptData),true)
	},
	// 用户小程序openId
	liteOpenId: (val) => {
		if(val){
			return uni.setStorageSync(liteOpenIdKey,sm4EncryptByReqData({ originData: val },true).encryptData)
		}
		return sm4DecryptByResData(uni.getStorageSync(liteOpenIdKey),true)
	},
	// 用户登录状态
	isLogin: (val) => {
		if (val !== undefined) {
			return uni.setStorageSync('isLogin',val)
		}
		return uni.getStorageSync('isLogin')
	},
	// 用户是否已归属网点
	isBind: (val) => {
		if (val !== undefined) {
			return uni.setStorageSync('isBind',val)
		}
		return uni.getStorageSync('isBind')
	},
	// 是否签到
	isSign: (val) => {
		if (val !== undefined){
			return uni.setStorageSync('isSign', val)
		}
		return uni.getStorageSync('isSign')
	},
	// 商户信息(长春)
	MCHS_CC: (val) => {
		if(val !== void 0){
			return uni.setStorageSync('MCHS_CC', val)
		}
		return uni.getStorageSync('MCHS_CC')
	},
	// 用户本地缓存的机构信息
	agentInfo: (val) => {
		if (val !== undefined){
			return uni.setStorageSync('agentInfo', val)
		}
		if (!uni.getStorageSync('agentInfo')){
			uni.setStorageSync('agentInfo', { agentNo: appConfig.locationAgentNo, agentName: appConfig.locationAgentName })	// 无值的时候取默认值
		}
		return uni.getStorageSync('agentInfo')
	},
	// 用户本地缓存的机构历史访问信息
	agentHistory: (val,isDelete = false) => {
		if (isDelete) {
			uni.removeStorageSync('agentHistory')
			return
		}
		if (val !== undefined){
			return uni.setStorageSync('agentHistory', val)
		}
		return uni.getStorageSync('agentHistory')
	}
}

export default model
